package com.testmall.config;

import com.testmall.entity.common.TokenProperties;
import com.testmall.interceptor.TokenInterceptor;
import com.testmall.utils.TokenUtil;
import com.testmall.utils.UserIdUtil;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Objects;

/**
 * @Description:
 * @Author: littleDesire
 * @Date: 2022-06-23 10:17
 * @Version: 1.0
 */
@Configuration
public class TokenConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor())
                .excludePathPatterns(tokenProperties().getExcludePathPatterns())
                .addPathPatterns(tokenProperties().getPathPatterns());
    }

    // 加载YML格式自定义配置文件
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        // File引入
        //yaml.setResources(new FileSystemResource(ResourceUtils.CLASSPATH_URL_PREFIX + "permission.yml"));
        // class引入，避免了路径处理问题
        yaml.setResources(new ClassPathResource("application.yaml"));
        configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
        return configurer;
    }

    @Bean
    public TokenUtil tokenUtil() {
        return new TokenUtil();
    }

    @Bean
    public TokenProperties tokenProperties() {
        return new TokenProperties();
    }

    @Bean
    public TokenInterceptor tokenInterceptor() {
        return new TokenInterceptor();
    }

    @Bean
    public UserIdUtil userIdUtil() {
        return new UserIdUtil();
    }}
